package com.ego.search.service.impl;

import com.ego.dubbo.service.TBItemCatDubboService;
import com.ego.dubbo.service.TBItemDubboService;
import com.ego.dubbo.service.TbItemDescDubboService;
import com.ego.pojo.TbItem;
import com.ego.pojo.TbItemCat;
import com.ego.pojo.TbItemDesc;
import com.ego.search.pojo.SearchPojo;
import com.ego.search.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.HighlightOptions;
import org.springframework.data.solr.core.query.HighlightQuery;
import org.springframework.data.solr.core.query.SimpleHighlightQuery;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {


    @Autowired
    private SolrTemplate solrTemplate;

    @DubboReference
    private TBItemDubboService tbItemDubboService;

    @DubboReference
    private TBItemCatDubboService tbItemCatDubboService;

    @DubboReference
    private TbItemDescDubboService tbItemDescDubboService;


    @Override
    public Map<String, Object> search(String q, int page, int size) {

        //创建条件对象
        Criteria criteria = new Criteria("item_keywords");
        criteria.is(q);


        //创建高亮查询对象
        HighlightQuery highlightQuery = new SimpleHighlightQuery(criteria);


        //设置分页
        highlightQuery.setOffset((long)size*(page-1));
        highlightQuery.setRows(size);


        //设置排序
        highlightQuery.addSort(Sort.by(Sort.Order.desc("_version_")));

        //设置高亮
        HighlightOptions highlightOptions = new HighlightOptions();
        highlightOptions.addField("item_title");
        highlightOptions.setSimplePrefix("<span style='color:red'>");
        highlightOptions.setSimplePostfix("</span>");

        highlightQuery.setHighlightOptions(highlightOptions);

        //执行搜索
        HighlightPage<SearchPojo> highlightPage = solrTemplate.queryForHighlightPage("ego", highlightQuery, SearchPojo.class);

        //获取总页页数
        int totalPages = highlightPage.getTotalPages();


        //创建集合：用于封装开发自己重新组装SearchPojo对象
        List<SearchPojo> searchPojoList = new ArrayList<>();

        //获取查询实体对象（所有非高亮的SearchPojo）
        //List<SearchPojo> content = highlightPage.getContent();
        //所有所有查询结果：solrweb管理器中搜索结果的 response ，包含非高亮数据和高亮数据
        List<HighlightEntry<SearchPojo>> highlighted = highlightPage.getHighlighted();
        for (HighlightEntry<SearchPojo> searchPojoHighlightEntry : highlighted) {
            //获取每次循环实体(非高亮)
            SearchPojo searchPojo = searchPojoHighlightEntry.getEntity();

            String img = "http://localhost:9000/images/a6847f73-0b3d-4028-80d8-59b8ad0dbb4c.jpg,http://localhost:9000/images/d589bfbd-a596-4990-87b8-acc76f2a1d73.jpg";
            String[] split = img.split(",");
            //SearchPojo 需要重新做 两件事情，1 ：设置 images 2，将高亮的数据设置 title中
            //1.设置 images
            searchPojo.setImages(StringUtils.isNoneBlank(searchPojo.getImage())?searchPojo.getImage().split(","):new String[1]);


            //2，将高亮的数据设置 title中
            //获取高亮数据
            List<HighlightEntry.Highlight> highlights = searchPojoHighlightEntry.getHighlights();

            //循环高亮数据
            for (HighlightEntry.Highlight highlight : highlights) {

                //如果是item_title
                if(highlight.getField().getName().equals("item_title")){
                    //获取高亮值
                    String highlightTitle = highlight.getSnipplets().get(0);

                    searchPojo.setTitle(highlightTitle);//将高亮的数据设置 title中
                }
            }
            searchPojoList.add(searchPojo);
        }


        Map<String,Object> result = new HashMap<>();
        result.put("totalPages",totalPages);
        result.put("query",q);
        result.put("itemList",searchPojoList);

        return result;
    }

    @Override
    public int insert(List<Long> ids) {


        List<SearchPojo> searchPojoList = new ArrayList<>();
        //根据id查询所有的商品
        List<TbItem> tbItems = tbItemDubboService.selectByIds(ids);

        for (TbItem item : tbItems) {

            SearchPojo sp = new SearchPojo();
            sp.setId(item.getId());
            sp.setTitle(item.getTitle());
            sp.setPrice(item.getPrice());
            sp.setImage(item.getImage());
            sp.setSellPoint(item.getSellPoint());

            //查询类目
            TbItemCat tbItemCat = tbItemCatDubboService.selectById(item.getCid());
            sp.setCatName(tbItemCat.getName());

            //查询描述
            TbItemDesc tbItemDesc = tbItemDescDubboService.selectByItemId(item.getId());
            sp.setDesc(tbItemDesc.getItemDesc());

            //将封装的SearchPojo添加到集合
            searchPojoList.add(sp);
        }


        UpdateResponse response = solrTemplate.saveBeans("ego", searchPojoList);
        int status = response.getStatus();
        System.out.println("status = " + status);
        //提交
        solrTemplate.commit("ego");

        return status==0?1:0;
    }

    @Override
    public int delete(List<String> ids) {
        UpdateResponse response = solrTemplate.deleteByIds("ego",ids);
        solrTemplate.commit("ego");
        return response.getStatus()==0?1:0;
    }

}
